﻿using Microsoft.AspNetCore.Authorization;
using nanhua.BookStore.DomainServices;
using nanhua.BookStore.Dto;
using nanhua.BookStore.Entitys.OrderAggregate;
using nanhua.BookStore.IApplicationServices;
using nanhua.BookStore.Orders;
using nanhua.BookStore.Permissions;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Volo.Abp.Application.Dtos;
using Volo.Abp.Application.Services;
using Volo.Abp.Domain.Repositories;
using Volo.Abp.Guids;

namespace nanhua.BookStore.ApplicationServices
{
    public class OrderAppService: ApplicationService, IOrderAppService
    {
        private readonly OrderManager _orderManager;
        private readonly IOrderRepository _orderRepository;
        private readonly IGuidGenerator _guidGenerator;

        public OrderAppService(OrderManager orderManager, IOrderRepository orderRepository, IGuidGenerator guidGenerator)
        {
            this._orderManager = orderManager;
            this._orderRepository = orderRepository;
            this._guidGenerator = guidGenerator;
        }
        [Authorize(BookStorePermissions.Orders.Create)]
        public async Task<bool> CreateOrderAsync(CreateOrderDto input)
        {
            Order order = new Order(this._guidGenerator.Create());
            foreach (var item in input.OrderDetails)
            {
                var orderDetail = _orderManager.CreateOrderDetail(item.ProductCode, item.Price);
                order.AddOrderDetail(orderDetail);
            }
            await _orderRepository.InsertAsync(order);
            return true;
        }
        [Authorize(BookStorePermissions.Orders.GetList)]
        public async Task<PagedResultDto<OrderDto>> GetListAsync(GetOrderListDto input)
        {
            if (input.Sorting.IsNullOrWhiteSpace())
            {
                input.Sorting = nameof(Order.CreationTime);
            }
            var orders = await _orderRepository.GetListAsync(input.SkipCount,input.MaxResultCount,input.Sorting);

            var totalCount = await _orderRepository.GetCountAsync();

            var results = ObjectMapper.Map<List<Order>, List<OrderDto>>(orders);

            return new PagedResultDto<OrderDto>(totalCount,
                results);
        }

        [Authorize(BookStorePermissions.Orders.Pay)]
        public async Task<bool> PayOrderAsync(PayOrderDto input)
        {
            var order = await _orderRepository.GetAsync(input.OrderId);
            order.Pay(input.PayType);
            await _orderRepository.UpdateAsync(order);
            return true;
        }
    }
}
